<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\TaskTemplate as TaskTemplateModer;
use app\admin\model\TaskCategory;
use app\admin\model\PayConfig;
use app\admin\model\TaskImgs;
use app\admin\model\Product;
use app\admin\model\ProductCategory;
use app\admin\model\SArea;
use app\admin\model\User;
use app\admin\model\DistributeTask;
use think\Db;
use think\Exception;

/**
 * 任务管理
 *
 * @icon   fa fa-list
 */
class TaskTemplate extends Backend
{

    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new TaskTemplateModer();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $zi = $this->request->request('zi','');
        $this->assignconfig('zi', $zi);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as &$v) {
                $v['category_name'] = TaskCategory::where(['id'=>$v['category_id']])->value('name');        
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $user_list =  User::field("nickname,id")->where(['is_task'=>1])->select();
            $this->view->assign('user_list', $user_list);
            //查询任务类目
            $category_list =  TaskCategory::select();
            $this->view->assign('category_list', $category_list);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $variate_name = $params['variate_name'];
        $variate_value = $params['variate_value'];
        $variate = [];
        foreach ($variate_name as $k=>$v) {
            if($v && !empty($variate_value[$k])){
                if(substr($variate_value[$k], -1) == '，' || substr($variate_value[$k], -1) == '，' ){
                    $variate_value[$k] = substr($variate_value[$k], 0, -1);
                }
                $variate[] = [
                    'variate_name'=>$v,
                    'variate_value'=>str_replace(' ','',str_replace('，',',',$variate_value[$k]))
                ];
            }else{
                $variate[] = [
                    'variate_name'=>'',
                    'variate_value'=>''
                ];
            }
        }
        $params['variate'] = json_encode($variate);
        unset($params['variate_name']);
        unset($params['variate_value']);
        $params['add_time'] = time();
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = TaskTemplateModer::insert($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }

    /**
     * 编辑
     *
     * @return string
     * @throws \think\Exception
     */
    public function edit($ids = null){
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //查询任务类目
        $category_list =  TaskCategory::select();
        $this->view->assign('category_list', $category_list);
        $variate = json_decode($row['variate'],true);
        $this->view->assign("variate", $variate);
        $this->view->assign("row", $row);
		if ($this->request->isPost()) {
			$params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);

            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $params[$this->dataLimitField] = $this->auth->id;
            }
            $variate_name = $params['variate_name'];
            $variate_value = $params['variate_value']; 
           
            $variate = [];
            foreach ($variate_name as $k=>$v) {
                if($v && !empty($variate_value[$k])){
                    if(substr($variate_value[$k], -3) == '，'){
                        $variate_value[$k] = substr($variate_value[$k], 0, -3);
                    }
                    if(substr($variate_value[$k], -1) == ','  ){
                        $variate_value[$k] = substr($variate_value[$k], 0, -1);
                    }
                    $variate[] = [
                        'variate_name'=>$v,
                        'variate_value'=> str_replace(' ','',str_replace('，',',',$variate_value[$k]))
                    ];
                }else{
                    $variate[] = [
                        'variate_name'=>'',
                        'variate_value'=>''
                    ];
                }
            }
            $params['variate'] = json_encode($variate);
            unset($params['variate_name']);
            unset($params['variate_value']);
            $params['add_time'] = time();
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    $this->model->validateFailException()->validate($validate);
                }
                
                $result = $row->allowField(true)->save($params); 
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error(__('No rows were inserted'));
            }else{
                $this->success('操作成功');
            }
        }
		return $this->view->fetch();
	}

    



     /**
     * 发布模版任务
     *
     * @return string
     * @throws \think\Exception
     */
    public function send_task($ids = '')
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->redirect('DistributeTask/product_add');
            return;
            $this->error(__('No Results were found'));
        }
        $row['category_name'] = TaskCategory::where(['id'=>$row['category_id']])->value('name');   
        $this->view->assign("row", $row);
        if (false === $this->request->isPost()) {
            $PayConfig = PayConfig::where(['name'=>'task'])->value('value');
            $PayConfig = json_decode($PayConfig,true);
            $type_arr = explode(',',$PayConfig['type_arr']);
            $this->view->assign('type_arr', $type_arr);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            //判断该模版类型
            if($row['type'] == 2){
                $category_name = explode(',',TaskCategory::where(['id'=>$row['category_id']])->value('chil_name'));
                if(!in_array($params['name'], $category_name)){
                    $this->error('该商品不在此类目关键词中,请确定模版选择是否正确');
                }
            }
            //判断该用户是否传了图片
            if($params['imgs']){
                //传了图片则存入图片库内
                $info = TaskImgs::where(['name'=>$params['name']])->find();
                if($info){
                    $imgs = $info['imgs'].','.$params['imgs'];
                }else{
                    $imgs = $params['imgs'];
                }
                TaskImgs::where(['id'=>$info['id']])->update(['imgs'=>$imgs]);
            }else{
                $info = TaskImgs::where(['name'=>$params['name']])->find();
                if(!$info){
                    $this->error('未查询到该商品有图片,需要上传相对于图片才可发布');
                }
                $imgs = $info['imgs'];
            }
            //开始添加任务
            $imgs = explode(',',$imgs);
            if(count($imgs) < $params['num']){
                $this->error('图片数量不够');
            }
            $variate = json_decode($row['variate'],true);
            for ($i=0; $i < $params['num']; $i++) { 
                $title = $row['title'];
                $content = $row['text'];
                foreach ($variate as $v) {
                    if($v['variate_name'] && $v['variate_value']){
                        $variate_value = explode(',',$v['variate_value']);
                        $content = str_replace($v['variate_name'],$variate_value[rand(0,count($variate_value)-1)],$content);
                        $title = str_replace($v['variate_name'],$variate_value[rand(0,count($variate_value)-1)],$title);
                    }
                }
                $content = str_replace('$name',$params['name'],$content);
                $title = str_replace('$name',$params['name'],$title);
                $index = rand(0,count($imgs)-1);
                $imgs_info = $imgs[$index];
                unset($imgs[$index]);
                sort($imgs);
                $arr = [
                    'add_time' => time(),
                    'title'=>$title,
                    'content'=>$content,
                    'status'=>-3,
                    'imgs'=> $imgs_info,
                    'task_type'=>$params['task_type'] ? $params['task_type'] : 1,
                    'type'=>$params['type'] ,
                    'product_id'=>$params['product_id'] ,
                    'character_type'=>$params['character_type'] ? $params['character_type'] : 1,
                    'category'=>$params['category']
                ];
                $result = DistributeTask::insert($arr);
            }
            TaskImgs::where(['id'=>$info['id']])->update(['imgs'=>implode(',',$imgs)]);


            $list = User::where(['is_task_subscription'=>1])->select();
            if($list){
                foreach ($list as $v) {
                    $data = [
                        "thing1"=>["value"=>'余享新任务已更新'],
                        "time3"=>["value"=>date('Y-m-d H:i:s',time())]
                    ];
                    send_subscription($v['id'],'xF751UgAPsa4BajwBin-BU6lG1riuvJsNxNpIPGM28c','/subone/user/distribute_task',$data);
                    User::where(['id'=>$v['id']])->update(['is_task_subscription'=>0]);
                }
            }

            
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }
}